<template>
  <div class="wrapper">
    <Card :bordered="false" :dis-hover="true" class="my-card-body">
      <div class="search-con search-con-top">
        <div class="mt addBtn">
          <Button type="primary" @click="addBtn" icon="md-add">新增管理员</Button>
        </div>
        <div class="mt">
          <Select
            v-model="role"
            clearable
            class="search-col search-common"
            placeholder="请选择角色"
          >
            <Option  v-for="item in roles" :value="item.roleId" :key="item.roleId">{{ item.roleName }}</Option>
          </Select>
        </div>
        <div class="mt">
          <Select
            v-model="org"
            clearable
            class="search-col search-common"
            placeholder="请选择项目点"
          >
            <Option  v-for="item in orgs" :value="item.orgId" :key="item.orgId">{{ item.name }}</Option>
          </Select>
        </div>
        <div class="mt">
          <Input
            clearable
            placeholder="请输入姓名、手机号"
            class="search-input search-common"
            v-model="searchKey"
          />
        </div>
        <div class="mt">
          <Button @click="handleSearch" class="search-btn" type="primary">
            <Icon custom="iconfont icon-sousuo" :size="16" />
            <span>查询</span>
          </Button>
        </div>
      </div>
      <Table border :columns="columns" :data="data" :stripe="true" class="tableMargin"></Table>
      <Page
        :total="pageTotal"
        :current="pageno"
        :page-size="pagesize"
        @on-change="handlePage"
        prev-text="上一页"
        next-text="下一页"
      />
    </Card>
    <drag-drawer
      v-model="showWindowBDrawer"
      :width.sync="width"
      :min-width="600"
      placement="right"
      :draggable="draggable"
      :scrollable="true"
    >
      <div slot="header">{{headerTitle}}</div>
      <div class="container">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100" label-position="right">
          <template v-if="isIndex==0">
            <FormItem label="姓名" prop="name">
              <Input v-model="formValidate.name" placeholder="请输入姓名"/>
            </FormItem>
            <FormItem label="手机账号" prop="phone">
              <Input v-model="formValidate.phone" placeholder="请输入手机账号"/>
            </FormItem>
            <FormItem label="个人照片">
              <upload uploadType="personalImg" :imgUrl="formValidate.img" @uploadData="uploadImgData" introText='上传个人照片'></upload>
            </FormItem>
          </template>
          <template v-else-if="isIndex==1">
            <Role :orgUserData="peopleList" :companyUserId='companyUserId' @orgUser="getOrgUserData" :pageTotal="orgTotal"></Role>
          </template>
        </Form>
      </div>
      <div slot="footer">
        <Button class="cancle" @click="showWindowBDrawer = false">取消</Button>
        <Button type="primary" v-if="isIndex==0" class="confirm" @click="handleSubmit('formValidate')">保存</Button>
        <Button type="primary" v-if="isIndex==1" class="confirm" @click="showWindowBDrawer = false">保存</Button>
      </div>
    </drag-drawer>
  </div>
</template>

<script>
import DragDrawer from "_c/drag-drawer";
import upload from "_c/upload/upload.vue";
import Role from "./check-role/check-role";
import { getCompanyUser, deleteCompanyUser,editCompanyUser,addCompanyUser,getOneCompanyUser,getCompanyUserOrg,addCompanyUserOrg,deleteCompanyUserOrg } from "@/api/staff";
import { getRoles } from "@/api/role";
import { getOrgs } from "@/api/org";
export default {
  inject: ["reload"],
  components: {
    DragDrawer,
    upload,
    Role
  },
  data () {
    return {
      roles:[],
      orgs:[],
      role:'',
      org:'',
      searchKey:'',
      // 分页
      pageTotal: null, //数据总数
      pageno: 1, //当前页码数
      pagesize: 10, //每页条数
      // 表格
      columns:[
        {
          title: "序号",
          type: "index",
          width: 100,
          align: "center"
        },
        {
          title: "姓名",
          key: "name",
          width: 160,
          align: "center",
        },
        {
          title: "手机账号",
          key: "phone",
          width: 200,
          align: "center",
        },
        {
          title: "角色",
          key: "roleText",
          align: "center",
          render:(h,params) =>{
              let length =params.row.roleText.length;
              if (length ==0 ||length==undefined){
                  return h("span",{},"无")
              }else if (length == 1){
                  return h("span",{},params.row.roleText[0])
              }else if (length > 1 ){
                  let roleName = '';
                  for (let i = 0 ; i<length;i++){
                      if (i==length-1){
                          roleName = roleName +  params.row.roleText[i];
                      }else{
                          roleName +=  params.row.roleText[i]+",";
                      }
                  }
                  return h("span",{},roleName)
              }
          }
        },
        {
          title: "项目点",
          key: "orgText",
          align: "center",
          render:(h,params) =>{
              let length =params.row.orgText.length;
              if (length ==0 ||length==undefined){
                  return h("span",{},"无")
              }else if (length == 1){
                  return h("span",{},params.row.orgText[0])
              }else if (length > 1 ){
                  return h("span",{},params.row.orgText[0]+"等"+length+"家项目点")
              }
          }
        },
        {
          title: "操作",
          align: "center",
          key: "operation",
          render: (h, params) => {
            if (params.row.manager) {
              return h("div", [
                h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small"
                      },
                      style: {
                        color: "#4074c7",
                        fontSize: "14px"
                      },
                      on: {
                        click: () => {
                          this.isIndex = 0
                          this.showWindowBDrawer = true;
                          this.headerTitle = "编辑管理者";
                          this.isEdit = 1;
                          this.companyUserId = params.row.companyUserId;
                          getOneCompanyUser(params.row.companyUserId).then(res=>{
                            this.formValidate = res.data.data;
                          })
                        }
                      }
                    },
                    "编辑"
                ),
                h("span", {}, "|"),
                h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small"
                      },
                      style: {
                        color: "#4074c7",
                        fontSize: "14px"
                      },
                      on: {
                        click: () => {
                          this.$confirm({
                            headTitle: "系统提示",
                            tip: `确定删除'${params.row.name}'管理者吗？`
                          })
                              .then(() => {
                                deleteCompanyUser(params.row.companyUserId).then(res => {
                                      if (res.data.code == 200||res.data.code == 204) {
                                        let data = {
                                          keyword: this.searchKey,
                                          pageno: this.pageno
                                        };
                                        this.getCompanyUserData(data);
                                        this.$Message.success("删除成功");
                                      } else {
                                        this.$Message.warning("删除失败");
                                      }
                                    }
                                );
                              })
                              .catch(() => {
                                console.log("no");
                              });
                        }
                      }
                    },
                    "删除"
                )
              ]);
            } else {
              return h("div", [
                h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small"
                      },
                      style: {
                        color: "#4074c7",
                        fontSize: "14px"
                      },
                      on: {
                        click: () => {
                          this.width = 800;
                          this.showWindowBDrawer = true;
                          this.disabled = true;
                          this.headerTitle = "关联项目点";
                          this.isIndex = 1;
                          this.orgTotal = null;
                          this.companyUserId = params.row.companyUserId;
                          this.getOrgUserData(params.row.companyUserId)
                        }
                      }
                    },
                    "关联项目点"
                ),
                h("span", {}, "|"),
                h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small"
                      },
                      style: {
                        color: "#4074c7",
                        fontSize: "14px"
                      },
                      on: {
                        click: () => {
                          this.isIndex = 0
                          this.showWindowBDrawer = true;
                          this.headerTitle = "编辑管理者";
                          this.isEdit = 1;
                          this.companyUserId = params.row.companyUserId;
                          getOneCompanyUser(params.row.companyUserId).then(res=>{
                            this.formValidate = res.data.data;
                          })
                        }
                      }
                    },
                    "编辑"
                ),
                h("span", {}, "|"),
                h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small"
                      },
                      style: {
                        color: "#4074c7",
                        fontSize: "14px"
                      },
                      on: {
                        click: () => {
                          this.$confirm({
                            headTitle: "系统提示",
                            tip: `确定删除'${params.row.name}'管理者吗？`
                          })
                              .then(() => {
                                deleteCompanyUser(params.row.companyUserId).then(res => {
                                      if (res.data.code == 200||res.data.code == 204) {
                                        let data = {
                                          keyword: this.searchKey,
                                          pageno: this.pageno
                                        };
                                        this.getCompanyUserData(data);
                                        this.$Message.success("删除成功");
                                      } else {
                                        this.$Message.warning("删除失败");
                                      }
                                    }
                                );
                              })
                              .catch(() => {
                                console.log("no");
                              });
                        }
                      }
                    },
                    "删除"
                )
              ]);
            }
          }
        }
      ],
      data:[],
      //抽屉
      isIndex:null,
      isEdit:0,
      headerTitle: "新增管理员",
      showWindowBDrawer: false,
      width: 800,
      draggable: true,
      formValidate:{
        name:'',
        phone:'',
        img:''
      },
      ruleValidate:{
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机账号', trigger: 'blur' }]
      },
      companyUserId:null,
      peopleList:[],
      orgTotal: null, //项目点总数
    }
  },
  methods: {
    addBtn(){
      this.headerTitle = '新增管理员';
      this.showWindowBDrawer = true;
      this.isEdit = 0;
      this.isIndex = 0;
      this.formValidate = {
        name:'',
        phone:'',
        img:''
      }
    },
    handleSearch(){
      let param={
          roleId:this.role,
          orgId:this.org,
          keyword: this.searchKey,
      }
      this.getCompanyUserData(param);
      this.pageno = 1;
    },
    handlePage(value) {
      this.pageno = value;
      let data = {
          roleId:this.role,
          orgId:this.org,
          keyword: this.searchKey,
          pageno: value
      };
      this.getCompanyUserData(data);
    },
    uploadImgData(data){
      this.formValidate.img = data.name;
    },
    getOrgUserData(userId,params) {
      getCompanyUserOrg(userId,params).then(res => {
        this.peopleList = res.data.data.list;
        this.orgTotal = res.data.data.total;
      }).then(()=>{
        this.getCompanyUserData();
      });
    },
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.isEdit == 0) {
            this.addCompanyUser();
          } else if (this.isEdit == 1) {
            this.editCompanyUser();
          }
        } else {
          console.log("验证失败");
        }
      });
    },
    // 获取所有人员
    getCompanyUserData(param){
      getCompanyUser(param).then(res => {
        let list = res.data.data.list;
        list.map(e=>{
          if(e.orgText != ''){
            e.orgText = e.orgText.split(',');
          }
          if(e.roleText != ''){
            e.roleText = e.roleText.split(',');
          }
        });
        this.data = list;
        this.pageTotal = res.data.data.total;
      });
    },
    addCompanyUser(){
      addCompanyUser(this.formValidate).then(res=>{
          if(res.data.code == 200|| res.data.code == 201  ){
              this.getCompanyUserData();
              this.showWindowBDrawer =false;
              this.$Message.success(res.data.msg);
          }
          return ;
      })
    },
    editCompanyUser(){
      editCompanyUser(this.companyUserId,this.formValidate).then(res=>{
          if(res.data.code == 200|| res.data.code == 201  ){
                this.$Message.success(res.data.msg);
          }
          return;
      }).then(()=>{
            let data = {
                  pageno: this.pagenow
              };
          this.getCompanyUserData(data);
          this.showWindowBDrawer =false;
      })
    },
    getRoles(){
      let params ={
          pagesize :100,
      }
      getRoles(params).then(res => {
        this.roles = res.data.data.list;
      });
    },
    getOrgs(){
      let params ={
          pagesize :100
      }
      getOrgs(params).then(res => {
          this.orgs = res.data.data.list;
      }).then(() =>{
          this.getCompanyUserData();
      })
    },
  },
  mounted(){
    this.getCompanyUserData();
    this.getRoles();
    this.getOrgs();
  }
}
</script>

<style>

</style>
